/*
  EOMono
  Copyright 2007, Adam Tauno Williams (Whitemice Consulting)
  License: LGPLv2  < http://www.gnu.org/licenses/lgpl-2.1.html >
 */
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using log4net;

[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension="log4net",Watch=true)]
namespace Whitemice.EOMono
{
  public static class EOManager
  {
    private static IDictionary<string, System.Type>  commands;
    private static readonly ILog log = LogManager.GetLogger(typeof(EOManager));
    
	  public static readonly bool isDebugEnabled = log.IsDebugEnabled;

	  public static ILog Log
	  {
	    get { return log; }
	  }
  
    static EOManager()
    {
      commands = new Dictionary<string, System.Type>();
      
      string currentDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
      string[] assemblyFilenames = Directory.GetFiles(currentDirectory, @"*.dll");
      foreach(string assemblyFilename in assemblyFilenames)
      {
        Assembly assembly = Assembly.LoadFile(assemblyFilename);
        foreach(Type assemblyType in assembly.GetExportedTypes())
		    {
		      if (assemblyType.GetInterface("IEOCommand") != null)
		      {
		        foreach (Object attribute in 
		          assemblyType.GetCustomAttributes(
		            typeof(Whitemice.EOMono.EOCommandAttribute), 
		            false))
		        {
		          Whitemice.EOMono.EOCommandAttribute eoattribute = 
		            (Whitemice.EOMono.EOCommandAttribute)attribute;
		          EOManager.Log.InfoFormat("Bonding command {0} with class {1}", eoattribute.Name, assemblyType.ToString());
		          commands.Add(eoattribute.Name, assemblyType);
		        } // end process attributes
		      } // end if-type-is-a-IEOCommand
		    } // end foreach-type
      } // end foreach-assembly
    } // end Init
    
    public static Type ClassForName(string _name)
    {
      if(commands.ContainsKey(_name))
        return commands[_name];
      return null;
    }
    
    public static string[] Commands 
    {
      get
      {
        int i = 0;
        string[] results = new string[commands.Count];
        foreach(string command in commands.Keys)
        {
          results[i] = command;
          i++;
        }
        return results;
      }
    }
  } // end class
} // end namespace
